# Create your tests here.


import math
import os
import threading

import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import scipy
from scipy import optimize
import docplex.mp.model as cplx
import xlrd
from scipy import optimize

from DataPlatform.settings import STATIC_ROOT
from business.models import ICE, GasBoiler, ElectricBoiler, AR, ERU, AirPump, GroundPump, GasTurbine, \
    WindPower, PVP, ARS, Buttery, OptConfig, OptResult, IceTank
from business.opt_predict import predict


class LoadParams:
    def __init__(self):
        self.heat, self.cold, self.elect, self.gas = [], [], [], []
        self.wind, self.solar = [], []


class Prices:
    def __init__(self):
        self.buy = {"elect": [], "gas": [], "heat": []}
        self.sell = {"elect": [], "gas": [], "heat": [], "cold": []}
        self.sell_net = []


class OptThread(threading.Thread):
    def __init__(self, who, mark):
        self.prc = 0
        self.msg = '正在计算中，请稍等'
        self.who = who
        self.mark = mark
        super(OptThread, self).__init__()

    def run(self):
        config = OptConfig.objects.get(opt_id=self.mark)
        params, prices = self.read_params(self.who, self.mark, config)
        is_success = compute(who=self.who, opt_id=self.mark, config=config, load_params=params, prices=prices)
        print("规划结果：", "有解" if is_success else "无解")
        if is_success:
            self.prc = 100
            self.msg = '规划完成'
        else:
            self.prc = 0
            self.msg = '计算失败，请重新配置'

    def get_result(self):
        # print(self.prc, self.msg)
        return self.prc, self.msg

    def read_params(self, who, mark, config: OptConfig):
        file_path = os.path.join(STATIC_ROOT + '/business/user_params_file/', who + '_opt_load_' + str(mark) + '.xlsx')
        data_work_boot = xlrd.open_workbook(file_path)
        prices = Prices()
        price_sheet = data_work_boot.sheets()[3]
        prices.buy['elect'] = [price_sheet.cell_value(i, 1) for i in range(1, price_sheet.nrows)]
        prices.buy['gas'] = [price_sheet.cell_value(i, 2) for i in range(1, price_sheet.nrows)]
        prices.buy['heat'] = [price_sheet.cell_value(i, 3) for i in range(1, price_sheet.nrows)]

        price_sheet = data_work_boot.sheets()[4]
        prices.sell['elect'] = [price_sheet.cell_value(i, 1) for i in range(1, price_sheet.nrows)]
        prices.sell['gas'] = [price_sheet.cell_value(i, 2) for i in range(1, price_sheet.nrows)]
        prices.sell['heat'] = [price_sheet.cell_value(i, 3) for i in range(1, price_sheet.nrows)]
        prices.sell['cold'] = [price_sheet.cell_value(i, 4) for i in range(1, price_sheet.nrows)]

        price_sheet = data_work_boot.sheets()[5]
        prices.sell_net = [price_sheet.cell_value(i, 1) for i in range(1, price_sheet.nrows)]

        load_params = LoadParams()

        self.prc = self.prc + 10
        self.msg = '正在预测热负荷'
        all_load = pd.read_excel(file_path).rename(columns=
                                                   {"热负荷（kW）": "heat", "冷负荷（kW）": "cold", "电负荷（kW）": "power",
                                                    "气负荷(kW)": "gas"})
        # load_params.heat = predict(file_path, "负荷", which_col="热负荷（kW）")
        load_params.heat = all_load.heat.values[:24]
        self.prc = self.prc + 10
        self.msg = '正在预测冷负荷'
        # load_params.cold = predict(file_path, "负荷", which_col="冷负荷（kW）")
        load_params.cold = all_load.cold.values[:24]
        self.prc = self.prc + 10
        self.msg = '正在预测电负荷'
        # load_params.elect = predict(file_path, "负荷", which_col="电负荷（kW）")
        load_params.elect = all_load.power.values[:24]
        self.prc = self.prc + 10
        self.msg = '正在预测气负荷'
        # load_params.gas = predict(file_path, "负荷", which_col="气负荷(kW)")
        load_params.gas = all_load.gas.values[:24]

        if config.wind_is_selected:
            self.prc = self.prc + 10
            self.msg = '正在预测风资源'
            load_params.wind = predict(file_path, "风资源数据", which_col="风速（m/s）")

        if config.solar_is_selected:
            self.prc = self.prc + 10
            self.msg = '正在预测光资源'
            load_params.solar = predict(file_path, "光资源数据", which_col="实际辐射照度（W/m2）")
        return load_params, prices


def compute(who, opt_id, config: OptConfig, load_params: LoadParams, prices: Prices):
    load_file = os.path.join(STATIC_ROOT + '/business/user_params_file/', who + '_opt_load_' + str(opt_id) + '.xlsx')
    opt_file = os.path.join(STATIC_ROOT + '/business/opt_compute_params/coef.xlsx')
    price_buy = pd.read_excel(load_file, sheet_name=3).rename(
        columns={"电价（元/kWh）": "power", "气价（元/kWh）": "gas", "热价（元/kWh）": "heat"})
    price_sell = pd.read_excel(load_file, sheet_name=4).rename(
        columns={"电（元/kWh）": "power", "气（元/kWh）": "gas", "热（元/kWh）": "heat", "冷（元/kWh）": "cold"})
    price_sell_net = pd.read_excel(load_file, sheet_name=5).rename(columns={"电（元/kWh）": "power"})
    load = pd.read_excel(load_file, 0).rename(
        columns={"热负荷（kW）": "heat", "冷负荷（kW）": "cold", "电负荷（kW）": "power", "气负荷(kW)": "gas"}).iloc[:, 2:]
    obj_c = DataFrame(data={
        "ele_buy": price_buy.power,
        "gas_buy": price_buy.gas,
        "heat_buy": price_buy.heat,
        "ele_sell": np.zeros(24),
        "CCHP_ele": np.zeros(24),
        "gp_h": np.zeros(24),
        "gp_c": np.zeros(24),
        "ap_ele": np.zeros(24),
        "gb_gas": np.zeros(24),
        "ar_gas": np.zeros(24),
        "eb_ele": np.zeros(24),
        "heat_ch": np.zeros(24),
        "heat_dis": np.zeros(24),
        "eru_ele": np.zeros(24),
        "coo_ch": np.zeros(24),
        "coo_dis": np.zeros(24),
        "ele_ch": np.zeros(24),
        "ele_dis": np.zeros(24),
        "wind": np.zeros(24),
        "pvp": np.zeros(24)
    })
    objc = obj_c.values.reshape(obj_c.shape[0] * obj_c.shape[1])

    el_cons_ele = pd.read_excel(opt_file, 1)
    el_cons_gas = pd.read_excel(opt_file, 2)
    el_cons_heat = pd.read_excel(opt_file, 3)
    el_cons_coo = pd.read_excel(opt_file, 4)

    # 选择设备
    power_ef = []
    cchp_max_power = []
    cchp_ele_c = []
    cchp_heat_c = []
    cchp_h = []
    if config.cchp_is_selected:
        if config.ice_is_selected:
            ice_object = ICE.objects
            target_ice = ice_object.get(model_name=config.ice_which) if config.ice_which else ice_object.get(
                is_default=True)
            target_gt = None
            for i in range(len(load_params.cold)):
                if load_params.cold[i] > 0:
                    cchp_ele_c.append(1)
                    cchp_heat_c.append(target_ice.heat_effect)
                    cchp_max_power.append(target_ice.max_power * config.ice_count)
                    power_ef.append(1 / target_ice.power_effect)
                    cchp_h.append(0)
                elif load_params.heat[i] > 0 and load_params.cold[i] == 0:
                    cchp_ele_c.append(1)
                    cchp_heat_c.append(0)
                    cchp_max_power.append(target_ice.max_power * config.ice_count)
                    power_ef.append(1 / target_ice.power_effect)
                    cchp_h.append(target_ice.heat_effect)
                else:
                    cchp_ele_c.append(1)
                    cchp_heat_c.append(0)
                    cchp_max_power.append(target_ice.max_power * config.ice_count)
                    power_ef.append(1 / target_ice.power_effect)
                    cchp_h.append(0)
        else:
            gt_object = GasTurbine.objects
            target_gt = gt_object.get(model_name=config.gt_which) if config.gt_which else gt_object.get(is_default=True)
            target_ice = None
            for i in range(len(load_params.cold)):
                if load_params.cold[i] > 0:
                    cchp_ele_c.append(1)
                    cchp_heat_c.append(target_gt.heat_effect)
                    cchp_max_power.append(target_gt.max_power * config.ice_count)
                    power_ef.append(1 / target_gt.generation_effect)
                    cchp_h.append(0)
                elif load_params.heat[i] > 0 and load_params.cold[i] == 0:
                    cchp_ele_c.append(1)
                    cchp_heat_c.append(0)
                    cchp_max_power.append(target_gt.max_power * config.gt_count)
                    power_ef.append(1 / target_gt.generation_effect)
                    cchp_h.append(target_gt.heat_effect)
                else:
                    cchp_ele_c.append(1)
                    cchp_heat_c.append(0)
                    cchp_max_power.append(target_gt.max_power * config.gt_count)
                    power_ef.append(1 / target_gt.generation_effect)
                    cchp_h.append(0)
    else:
        target_gt = None
        target_ice = None
        power_ef = np.zeros(len(load_params.cold))
        cchp_max_power = np.zeros(len(load_params.cold))
        cchp_ele_c = np.zeros(len(load_params.cold))
        cchp_heat_c = np.zeros(len(load_params.cold))
        cchp_h = np.zeros(len(load_params.cold))

    if config.ars_is_selected:
        ars_object = ARS.objects
        target_ars = ars_object.get(model_name=config.ars_which) if config.ars_which else ars_object.get(
            is_default=True)
    else:
        target_ars = None

    if config.ap_is_selected:
        ap_object = AirPump.objects
        target_ap = ap_object.get(model_name=config.ap_which) if config.ap_which else ap_object.get(
            is_default=True)
    else:
        target_ap = None

    if config.gb_is_selected:
        gb_object = GasBoiler.objects
        target_gb = gb_object.get(model_name=config.gb_which) if config.gb_which else gb_object.get(
            is_default=True)
    else:
        target_gb = None

    if config.ar_is_selected:
        ar_object = AR.objects
        target_ar = ar_object.get(model_name=config.ar_which) if config.ar_which else ar_object.get(
            is_default=True)
    else:
        target_ar = None

    if config.eb_is_selected:
        eb_object = ElectricBoiler.objects
        target_eb = eb_object.get(model_name=config.eb_which) if config.eb_which else eb_object.get(
            is_default=True)
    else:
        target_eb = None

    if config.gp_is_selected:
        gp_object = GroundPump.objects
        target_gp = gp_object.get(model_name=config.gp_which) if config.gp_which else gp_object.get(
            is_default=True)
    else:
        target_gp = None

    if config.wind_is_selected:
        wd_object = ElectricBoiler.objects
        target_wd = wd_object.get(model_name=config.wind_which) if config.wind_which else wd_object.get(
            is_default=True)
    else:
        target_wd = None

    if config.battery_is_selected:
        battery_object = Buttery.objects
        target_battery = battery_object.get(
            model_name=config.battery_which) if config.battery_which else battery_object.get(
            is_default=True)
    else:
        target_battery = None

    if not target_wd or len(load_params.wind) == 0:
        wind_source = Series(np.zeros(24))
    else:
        wind_source = Series(load_params.wind)

    wind_opt_params = wind_source.map(lambda x: math.floor(x)).map(
        lambda x: target_wd['s' + str(x)] if 25 >= x >= 2 else 0).values

    if config.solar_is_selected:
        solar_object = PVP.objects
        target_solar = solar_object.get(model_name=config.solar_which) if config.solar_which else solar_object.get(
            is_default=True)
    else:
        target_solar = None

    if config.cu_is_selected:
        eru_object = ERU.objects
        target_eru = eru_object.get(model_name=config.cu_which) if config.cu_which else eru_object.get(
            is_default=True)
    else:
        target_eru = None

    if config.it_is_selected:
        target_it = IceTank.objects.get(model_name=config.it_which) if config.it_which else IceTank.objects.get(
            is_default=True)
    else:
        target_it = None

    if config.heat_storage_is_selected:
        hs_max_cap = config.heat_storage_max_capacity
        hs_ch_power = config.heat_storage_max_powerch
        hs_dis_power = config.heat_storage_max_powerdis
        hs_ef = config.heat_storage_efficiency
    else:
        hs_max_cap = 0
        hs_ch_power = 0
        hs_dis_power = 0
        hs_ef = 0

    if not target_solar and len(load_params.solar) > 0:
        solar_source = Series(load_params.solar).map(lambda x: x / target_solar.max_power)
    else:
        solar_source = Series(np.zeros(24))

    # 上限约束
    ub_ = pd.read_excel(opt_file, 0)
    # 部分参数需要根据用户的具体配置，完善矩阵信息
    ub_['ele_buy'] = np.zeros(24) if config.model_which == 0 else np.array([999999] * 24)
    ub_['gas_buy'] = np.array([config.gas_max_output] * 24) if config.model_buy_gas else np.zeros(24)
    ub_['heat_buy'] = np.array([config.heat_max_output] * 24) if config.model_buy_heat else np.zeros(24)
    ub_['ele_sell'] = np.array([999999] * 24) if config.model_which == 2 else np.zeros(24)

    ub_['CCHP_ele'] = cchp_max_power
    ub_['gp_h'] = config.gp_count * target_gp.input_heat_power if target_gp else 0
    ub_['gp_c'] = config.gp_count * target_gp.input_cool_power if target_gp else 0
    ub_['ap_ele'] = config.ap_count * target_ap.input_power if target_ap else 0
    ub_['gb_gas'] = config.gb_count * target_gb.max_in_power if target_gb else 0
    ub_['ar_gas'] = config.ar_count * target_ar.income_cool if target_ar else 0
    ub_['eb_ele'] = config.eb_count * target_eb.max_in_power if target_eb else 0
    ub_['heat_ch'] = config.heat_storage_max_powerch if config.heat_storage_is_selected else 0
    ub_['heat_dis'] = config.heat_storage_max_powerdis if config.heat_storage_is_selected else 0
    ub_['eru_ele'] = config.cu_count * target_eru.input_cool_power if target_eru else 0
    ub_['coo_ch'] = config.cu_count * target_eru.input_ice_power if target_eru else 0
    ub_['coo_dis'] = config.cu_count * target_eru.input_ice_power if target_eru else 0
    ub_['ele_ch'] = config.battery_count * target_battery.u_cdp if target_battery else 0
    ub_['ele_dis'] = config.battery_count * target_battery.u_cdp if target_battery else 0
    ub_['wind'] = config.wind_count
    ub_['pvp'] = config.solar_count

    # 下限约束
    lb_ = ub_.copy()
    r, c = lb_.shape
    for i in range(r):
        lb_.iloc[i] = 0

    new_size = ub_.shape[0] * ub_.shape[1]

    ubs = ub_.T.values.reshape(new_size)
    lbs = lb_.values.reshape(lb_.shape[0] * lb_.shape[1])

    # 电平衡
    cgp_h = []
    cgp_c = []
    cgph = []
    cgpc = []
    if not target_gp:
        cgp_h = np.zeros(len(load_params.cold))
        cgp_c = np.zeros(len(load_params.cold))
        cgph = np.zeros(len(load_params.cold))
        cgpc = np.zeros(len(load_params.cold))
    else:
        for i in range(len(load_params.cold)):
            if load_params.cold[i] >= 0 and load_params.heat[i] == 0:
                cgp_h.append(0)
                cgp_c.append(1 / target_gp.make_cool_effect)
                cgph.append(0)
                cgpc.append(1)
            elif load_params.cold[i] == 0 and load_params.heat[i] == 0:
                cgp_h.append(0)
                cgp_c.append(0)
                cgph.append(0)
                cgpc.append(0)
            elif load_params.cold[i] == 0 and load_params.heat[i] >= 0:
                cgp_h.append(1 / target_gp.make_heat_effect)
                cgp_c.append(0)
                cgph.append(1)
                cgpc.append(0)
            else:
                cgp_h.append(0)
                cgp_c.append(1 / target_gp.make_cool_effect)
                cgph.append(1)
                cgpc.append(1)
        cgp_h = np.array(cgp_h)
        cgp_c = np.array(cgp_c)
        cgph = np.array(cgph)
        cgpc = np.array(cgpc)

    el_cons_ele['CCHP_ele'] = cchp_ele_c
    el_cons_ele['gp_h'] = - cgp_h
    el_cons_ele['gp_c'] = - cgp_c
    el_cons_ele['ap_ele'] = -1 if target_ap else 0
    el_cons_ele['eb_ele'] = -1 if target_eb else 0
    el_cons_ele['eru_ele'] = -1 if target_eru else 0
    el_cons_ele['coo_ch'] = - config.cu_count * target_eru.ice_effect if target_eru else 0
    el_cons_heat['heat_ch'] = 0
    el_cons_ele['ele_ch'] = -1 if target_battery else 0
    el_cons_ele['ele_dis'] = 1 if target_battery else 0
    el_cons_ele['wind'] = config.wind_count * wind_opt_params if config.wind_is_selected else 0
    el_cons_ele['pvp'] = config.solar_count * solar_source if config.solar_is_selected else 0

    el_cons_gas['CCHP_ele'] = - np.array(power_ef)
    el_cons_gas['gb_gas'] = -1 if target_gb else 0
    el_cons_gas['ar_gas'] = -1 if target_ap else 0

    el_cons_heat['CCHP_ele'] = np.multiply(np.array(power_ef), np.array(cchp_h))
    el_cons_heat['gp_h'] = cgph
    el_cons_heat['gb_gas'] = target_gb.heat_effect if target_gb else 0
    el_cons_heat['eb_ele'] = target_eb.heat_effect if target_eb else 0
    el_cons_heat['heat_ch'] = -1 if config.heat_storage_is_selected else 0
    el_cons_heat['heat_dis'] = 1 if config.heat_storage_is_selected else 0

    el_cons_coo['CCHP_ele'] = np.multiply(np.array(power_ef), np.array(cchp_heat_c)) * target_ars.effect
    el_cons_coo['gp_c'] = cgpc
    el_cons_coo['ap_ele'] = target_ap.effect if target_ap else 0
    el_cons_coo['ar_gas'] = target_ar.cool_effect if target_ar else 0
    el_cons_coo['eru_ele'] = target_eru.cool_effect if target_eru else 0
    el_cons_coo['coo_ch'] = -1 if target_eru else 0
    el_cons_coo['coo_dis'] = 1 if target_eru else 0

    eql_ele = el_cons_ele.T.values
    eql_gas = el_cons_gas.T.values
    eql_heat = el_cons_heat.T.values
    eql_coo = el_cons_coo.T.values

    b_e = load.power.values
    b_g = load.gas.values
    b_h = load.heat.values
    b_c = load.cold.values

    m, n = obj_c.shape
    range_row = range(1, n + 1)
    range_column = range(1, m + 1)

    # 下界
    l = {(i, t): lbs[(i - 1) * m + t - 1] for i in range_row for t in range_column}
    # 上界
    u = {(i, t): ubs[(i - 1) * m + t - 1] for i in range_row for t in range_column}
    # 目标函数系数
    c = {(i, t): objc[(i - 1) * m + t - 1] for i in range_row for t in range_column}
    # eql ct 系数
    ae = {(i, t): eql_ele[i - 1, t - 1] for i in range_row for t in range_column}
    ag = {(i, t): eql_gas[i - 1, t - 1] for i in range_row for t in range_column}
    ah = {(i, t): eql_heat[i - 1, t - 1] for i in range_row for t in range_column}
    ac = {(i, t): eql_coo[i - 1, t - 1] for i in range_row for t in range_column}
    # 负荷
    be = {t: b_e[t - 1] for t in range_column}
    bg = {t: b_g[t - 1] for t in range_column}
    bh = {t: b_h[t - 1] for t in range_column}
    bc = {t: b_c[t - 1] for t in range_column}

    opt_model = cplx.Model(name="MIP Model")
    # 变量
    x_vars = {(i, t): opt_model.continuous_var(lb=l[i, t], ub=u[i, t], name="x_{0}_{1}".format(i, t)) for i in range_row
              for
              t in range_column}

    # 目标函数
    objective = opt_model.sum(x_vars[i, t] * c[i, t] for i in range_row for t in range_column)

    cte = {t: opt_model.add_constraint(ct=opt_model.sum(ae[i, t] * x_vars[i, t] for i in range_row) == be[t],
                                       ctname="constraint_{0}".format(t)) for t in range_column}
    ctg = {t: opt_model.add_constraint(ct=opt_model.sum(ag[i, t] * x_vars[i, t] for i in range_row) == bg[t],
                                       ctname="constraint_{0}".format(t)) for t in range_column}
    cth = {t: opt_model.add_constraint(ct=opt_model.sum(ah[i, t] * x_vars[i, t] for i in range_row) == bh[t],
                                       ctname="constraint_{0}".format(t)) for t in range_column}
    ctc = {t: opt_model.add_constraint(ct=opt_model.sum(ac[i, t] * x_vars[i, t] for i in range_row) == bc[t],
                                       ctname="constraint_{0}".format(t)) for t in range_column}

    # 储能约束
    dis = np.ones(24)
    ch = -np.ones(24)
    charge = np.concatenate((ch, dis))
    storage_c = opt_model.add_constraint(
        ct=opt_model.sum(charge[(i - 14) * m + t - 1] * x_vars[i, t] for i in range(14, 16) for t in range_column) == 0)
    storage_h = opt_model.add_constraint(
        ct=opt_model.sum(charge[(i - 11) * m + t - 1] * x_vars[i, t] for i in range(11, 13) for t in range_column) == 0)
    storage_e = opt_model.add_constraint(
        ct=opt_model.sum(charge[(i - 16) * m + t - 1] * x_vars[i, t] for i in range(16, 18) for t in range_column) == 0)

    # 容量约束

    if config.cu_is_selected:
        storage_c = opt_model.add_constraint(ct=opt_model.sum(x_vars[14, t] for t in range_column) == 0)
    if config.heat_storage_is_selected:
        storage_h = opt_model.add_constraint(ct=opt_model.sum(x_vars[11, t] for t in range_column) == 0)
    if config.battery_is_selected:
        storage_e = opt_model.add_constraint(ct=opt_model.sum(x_vars[16, t] for t in range_column) == 0)

    opt_model.minimize(objective)
    opt_model.solve()
    print(opt_model.solve_details.status)
    if opt_model.solve_details.status == 'infeasible':
        return False

    opt_df = pd.DataFrame.from_dict(x_vars, orient="index", columns=["variable_object"])
    opt_df["solution_value"] = opt_df["variable_object"].apply(lambda item: item.solution_value)
    opt_df.drop(columns=["variable_object"], inplace=True)

    resx = np.rint(opt_df.solution_value.values).reshape((20, 24))

    ele_buy = resx[0]
    gas_buy = resx[1]
    heat_buy = resx[2]
    ele_sell = resx[3]

    cchp_e = resx[4]
    cchp_g = resx[4] / power_ef if config.cchp_is_selected else resx[4] * 0
    cchp_h = resx[4] * target_ars.effect if target_ars else resx[4] * 0
    cchp_c = resx[4] * target_ars.effect if target_ars else resx[4] * 0

    gp_h = resx[5]
    gp_c = resx[6]
    for i in range_column:
        if load_params.heat[i] > 0:
            gp_ele = resx[5] / target_gp.make_heat_effect if config.gp_is_selected else resx[5] * 0
        elif load_params.heat[i] == 0 and load_params.cold[i] > 0:
            gp_ele = resx[6] / target_gp.make_cool_effect if config.gp_is_selected else resx[6] * 0
        else:
            gp_ele = resx[5] * 0

    ap_ele = resx[7]
    ap_coo = resx[7] * target_ap.effect if target_ap else resx[7] * 0

    gb_gas = resx[8]
    gb_heat = resx[8] * target_gb.heat_effect if target_gb else resx[8] * 0

    ar_gas = resx[9]
    ar_coo = resx[9] * target_ar.cool_effect if target_ar else resx[9] * 0

    eb_ele = resx[10]
    eb_heat = resx[10] * target_eb.heat_effect if target_eb else resx[10] * 0
    heat_ch = resx[11]
    heat_dis = resx[12]

    eru_ele = resx[13]
    coo_ch = resx[14]
    coo_dis = resx[15]
    eru_c = resx[13] * target_eru.cool_effect if target_eru else resx[13] * 0

    ele_ch = resx[16]
    ele_dis = resx[17]

    wind = resx[18]
    wind_power = resx[18] * wind_opt_params
    pvp = resx[19]
    pvp_power = resx[19] * solar_source

    range_result = 24
    for i in range(range_result):
        rst = {
            'opt_id': opt_id,
            'target_date': opt_id,
            'target_time': i,
            'ice_os': cchp_e[i],
            'ice_ig': cchp_g[i],
            'gp_ieh': gp_ele[i],
            'gp_oh': gp_h[i],
            'gp_oc': gp_c[i],
            'ap_ie': ap_ele[i],
            'ap_oc': ap_coo[i],
            'gb_ig': gb_gas[i],
            'gb_oh': gb_heat[i],
            'ar_ig': ar_gas[i],
            'ar_oc': ar_coo[i],
            'eb_ie': eb_ele[i],
            'eb_oh': eb_heat[i],
            'it_ch': coo_ch[i],
            'it_dis': coo_dis[i],
            'ele_buy': ele_buy[i],
            'ele_pri': prices.buy['elect'][i] * ele_buy[i],
            'gas_buy': gas_buy[i],
            'gas_pri': prices.buy['gas'][i] * gas_buy[i],
            'heat_buy': heat_buy[i],
            'heat_pri': prices.buy['heat'][i] * heat_buy[i],
            'ele_sell': ele_sell[i],
            'ele_inc': ele_sell[i] * prices.sell["elect"][i],
            'wind': wind[i],
            'PV': pvp[i],
            'cchp_oh': cchp_h[i],
            'cchp_oc': cchp_c[i],
            'heat_load': load_params.heat[i],
            'cold_load': load_params.cold[i],
            'ele_load': load_params.elect[i],
            'sell_h': load_params.heat[i] * prices.sell["heat"][i],
            'sell_c': load_params.cold[i] * prices.sell["cold"][i],
            'sell_e': load_params.elect[i] * prices.sell["elect"][i],
            'wind_power': wind_power[i],
            'pvp_power': pvp_power[i],
            'co2_em': gas_buy[i] * 0.589,
            'nox_em': gas_buy[i] * 0.000378,
            'ele_ch': ele_ch[i],
            'ele_dis': ele_dis[i],
            'heat_store': heat_ch[i],
            'heat_release': heat_dis[i],
            'ice_store': coo_ch[i],
            'ice_dis': coo_dis[i],
            "eru_ele": eru_ele[i],
            "eru_c": eru_c[i],
            'is_correct': True
        }  # 对应计算excel里的结果
        OptResult(**rst).save()
        print("i:", i, "rst:", rst)
    return True
